package com.logos.ruralrevitalization.service.impl;

import com.logos.ruralrevitalization.req.ChatReq;
import com.logos.ruralrevitalization.service.ChatService;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionRequest;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
import com.volcengine.ark.runtime.service.ArkService;
import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service("chatServiceImpl")
public class ChatServiceImpl implements ChatService {

    public static final String apiKey = "c137ee7b-cd87-4b15-8b51-7c5431729c2c";

    public static final String url = "https://ark.cn-beijing.volces.com/api/v3/chat/completions";

    //    public static final String question = "你是谁";
    public static ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS);
    public static Dispatcher dispatcher = new Dispatcher();
    // The output time of the reasoning model is relatively long. Please increase the timeout period.
    public static ArkService service = ArkService.builder()
            .timeout(Duration.ofSeconds(1800))
            .connectTimeout(Duration.ofSeconds(20))
            .dispatcher(dispatcher)
            .connectionPool(connectionPool)
            .baseUrl(url)
            .apiKey(apiKey)
            .build();

    @Override
    public String chat(ChatReq chatReq) {
        final List<ChatMessage> streamMessages = new ArrayList<>();
        final ChatMessage streamUserMessage = ChatMessage.builder()
                .role(ChatMessageRole.USER)
                .content(chatReq.getMessage())
                .build();
        streamMessages.add(streamUserMessage);

        ChatCompletionRequest streamChatCompletionRequest = ChatCompletionRequest.builder()
                .model("deepseek-r1-250120")
                .messages(streamMessages)
                .build();

        StringBuilder sbRet = new StringBuilder();
        try {
            service.streamChatCompletion(streamChatCompletionRequest)
                    .doOnError(Throwable::printStackTrace)
                    .blockingForEach(
                            delta -> {
                                if (!delta.getChoices().isEmpty()) {
                                    String content = (String) delta.getChoices().get(0).getMessage().getContent();
                                    if (StringUtils.isNotEmpty(content)) {
                                        // 清理多余换行符
                                        content = content.replaceAll("\\s+", " ").trim();
                                        sbRet.append(content);
                                    }
                                }
                            }
                    );
        } catch (Exception e) {
            e.printStackTrace();
            return "服务器繁忙,稍后再试";
        }
        // 最终返回前再次清理
        return sbRet.toString().replaceAll("\\s+", " ").trim();
    }

}
